package org.yourscrum.persistence;

import org.yourscrum.domain.Story;
import org.yourscrum.domain.StoryRepository;
import org.yourscrum.domain.Theme;
import org.yourscrum.domain.Task;
import org.springframework.stereotype.Repository;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.FetchPlan;
import java.util.List;

/**
 * @author Jettro Coenradie
 */
@Repository("storyRepository")
public class JdoStoryRepository extends JdoRepository implements StoryRepository {

    public Story createStory(Story story) {
        return storeEntity(story);
    }

    public Story updateStory(final Story story) {
        return new RepositoryCallback<Story>(getPmFactory()) {
            Story doUseRepository(PersistenceManager pm) {
                pm.makePersistent(story);
                return story;
            }
        }.useRepository();
    }

    public Story obtainStoryById(final long id) {
        return new RepositoryCallback<Story>(getPmFactory()) {
            Story doUseRepository(PersistenceManager pm) {
                Story story = pm.getObjectById(Story.class, id);
                pm.getFetchPlan().setDetachmentOptions(FetchPlan.DETACH_LOAD_FIELDS);
                /* TODO jettro : Want to remove this, but is necessary for storage
                   For some reason the detaching does not work as expeced, also detaching can not take place
                   when interacting with the object (like adding a task in the domain service classes through
                   the domain objects does not work.
                   return pm.detachCopy(story);
                 */
                for (Task task : story.getTasks()) {}
                return story;
            }
        }.useRepository();
    }

    public List<Story> listAllStories() {
        return new RepositoryCallback<List<Story>>(getPmFactory()) {

            List<Story> doUseRepository(PersistenceManager pm) {
                Query query = pm.newQuery(Story.class);
                List<Story> result = (List<Story>) query.execute();
                pm.getFetchPlan().setDetachmentOptions(FetchPlan.DETACH_LOAD_FIELDS);
                return (List<Story>) pm.detachCopyAll(result);
            }
        }.useRepository();
    }

    public List<Story> listAllStories(Theme theme) {
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }


}
